package com.fenghongzhang.day015;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    private ListView lv;
    private MediaPlayer mediaPlayer ;
    private List<Music> list;
    private SeekBar seekBar;
    private Timer timer;
    private Button model;

    //播放模式的判断
    private int playModel = 0;
    //播放的下标的缓存
    private int index = 0;

    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        model = (Button) findViewById(R.id.model);

        //创建播放器对象
        mediaPlayer = new MediaPlayer();//内存泄漏

        lv = (ListView) findViewById(R.id.lv);
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        list = new ArrayList<>();


        if(Build.VERSION.SDK_INT >=  Build.VERSION_CODES.M){
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},999);
        }

        //进度条
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(final AdapterView<?> parent, View view, int position, long id) {
                try {
                    index = position;
                    play(position);

                    //播放错误监听
                    mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                        @Override
                        public boolean onError(MediaPlayer mp, int what, int extra) {
                            return false;
                        }
                    });

                    //播放完成监听
                    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            switch (playModel){
                                case MusicUtil.RANDOM:
                                    //随机
                                    int i = new Random().nextInt(list.size());
                                    play(i);
                                    break;
                                    //单曲
                                case MusicUtil.SINGLE:
                                    play(index);
                                    break;
                                    //顺序播放
                                case MusicUtil.ORDER:
                                    next();
                                    break;
                            }

                        }
                    });

                    if(timer == null){
                        timer = new Timer();
                        timer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                //最大值
                                seekBar.setMax(mediaPlayer.getDuration());//0
                                //进度值
                                seekBar.setProgress(mediaPlayer.getCurrentPosition());
                            }
                        },2000,1000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //播放的方法
    private void play(int position)  {
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(list.get(position).getData());
            mediaPlayer.prepareAsync();//异步加载
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
//
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 999  && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            //读取sd中的音乐,填充到lv中.
            ContentResolver contentResolver = getContentResolver();
            Cursor query = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
            if(query != null){
                while (query.moveToNext()){
                    String title = query.getString(query.getColumnIndex(MediaStore.Audio.Media.TITLE));
                    String artist = query.getString(query.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                    String duartion = query.getString(query.getColumnIndex(MediaStore.Audio.Media.DURATION));
                    String data = query.getString(query.getColumnIndex(MediaStore.Audio.Media.DATA));
                    String size = query.getString(query.getColumnIndex(MediaStore.Audio.Media.SIZE));
                    String ablumId = query.getString(query.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                    //过滤短音频
                    if (Integer.parseInt(duartion) >= 1000 * 60){
                        Music music = new Music(title,artist,duartion,data,size,ablumId);
                        list.add(music);
                    }

                }
                query.close();
            }
            MyAdapter myAdapter = new MyAdapter(list, this);
            lv.setAdapter(myAdapter);
        }else{
            finish();
        }
    }


    public void pause(View view) {
        mediaPlayer.pause();
    }

    public void stop(View view) {
        mediaPlayer.stop();
    }

    public void restart(View view) {
        mediaPlayer.start();
    }

    //播放模式
    public void model(View view) {
        final PopupWindow popupWindow = new PopupWindow();

        View inflate = LayoutInflater.from(this).inflate(R.layout.pop_layout, null);
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setContentView(inflate);
        TextView order = inflate.findViewById(R.id.pop_order);
        order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "顺序", Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
                playModel = MusicUtil.ORDER;
            }
        });

        TextView random = inflate.findViewById(R.id.pop_random);
        random.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "随机", Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
                playModel = MusicUtil.RANDOM;
            }
        });

        TextView single = inflate.findViewById(R.id.pop_single);
        single.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "单曲", Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
                playModel = MusicUtil.SINGLE;
            }
        });


        popupWindow.setOutsideTouchable(true);

        popupWindow.showAsDropDown(model,0,-350);

    }

    //点击事件
    public void next(View view) {
        next();
    }

    //下首
    private void next() {
        index++;
        if (index >= list.size() - 1) {
            index = 0;
        }
        play(index);
    }

    //上首
    public void pre(View view) {
        index--;
        if (index <= 0) {
            index = 0;
        }
        play(index);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: ");
//        timer.cancel();
//        mediaPlayer.stop();
//        mediaPlayer.release();
//        mediaPlayer = null;
    }
}
